package com.edu.control.util;

import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <pre>
 * OkHttp官方文档并不建议我们创建多个OkHttpClient,因此全局使用一个.
 *
 * </pre>
 *
 * @author hzl
 * @date
 */
public class OkHttpUtil {

    private static String username = "admin";

    private static String password = "admin";

    public static void setUsername(String username) {
        OkHttpUtil.username = username;
    }

    public static void setPassword(String password) {
        OkHttpUtil.password = password;
    }

    private static final OkHttpClient OPENFAAS_API_CLIENT = new OkHttpClient().newBuilder()
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request original = chain.request();
                    // Request customization: add request headers
                    Request.Builder requestBuilder = original.newBuilder()
                            .addHeader("Authorization", Credentials.basic("admin", password));
                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            })
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.MINUTES)
            .writeTimeout(5, TimeUnit.MINUTES)
            .build();

    public static Response execute(Request request) throws IOException {
        return OPENFAAS_API_CLIENT.newCall(request).execute();
    }
}
